package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private ClazzService clazzService;
    /**
     * 分页查询
     *
     * @param student
     */
    @Override
    public PageResult<Student> getPageResult(StudentQueryParam student) {
        Page<Student> page = Page.of(student.getPage(),student.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));
        // 使用lambdaQuery方法构建查询条件
        page=lambdaQuery().like(student.getName()!=null && !student.getName().isEmpty(),Student::getName,student.getName())
                .eq(student.getDegree()!=null, Student::getDegree,student.getDegree())
                .eq(student.getClazzId()!=null, Student::getClazzId,student.getClazzId())
                .page(page);
        //获取学生集合
        List<Student> students=page.getRecords();
        //获取所有学生的班级id
        List<Integer> clazzids=students.stream().map(student1 -> student1.getClazzId()).collect(Collectors.toList());
        if (!clazzids.isEmpty()){
            //批量查询这些班级信息
            List<Clazz> clazzes = clazzService.listByIds(clazzids);
            //将班级名称封装到学生对象中
            students.forEach(student1 -> {
                clazzes.forEach(clazz -> {
                    if (student1.getClazzId()!=null && student1.getClazzId().equals(clazz.getId())){
                        student1.setClazzName(clazz.getName());
                    }
                });
            });


        }
        return new  PageResult<>(page.getTotal(),students);
    }

    /**
     * 学员违纪
     *
     * @param id
     * @param score
     */
    @Override
    public void violation(Integer id, Integer score) {
        LambdaUpdateWrapper<Student> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Student::getId,id)
                .setSql("violation_count=violation_count+1")
                .setSql("violation_score=violation_score+"+score);
        update(wrapper);
    }
}
